package com.replication.jdbc;

import java.util.ArrayList;
import java.util.List;

import com.replication.logging.Logger;


public class URLParser {
    private static Logger logger = Logger.getLogger(URLParser.class);
    private String replicationUrl ;
    
    private String masterUrl;
    private final List<String> slaverUrlList = new ArrayList<String>();
    
    public URLParser(String replicationUrl){
        this.replicationUrl = replicationUrl;
        parser();
    }
    
    private void parser(){
    	logger.debug("{Parser URL} " + replicationUrl);
        String driverPrefix = replicationUrl.substring(URLPrefix.URL_PREFIX.length(),replicationUrl.indexOf("//"));
        String dbserverHostsStr = replicationUrl.substring(replicationUrl.indexOf("//")+2,replicationUrl.lastIndexOf('/'));
        String databaseOpts = replicationUrl.substring(replicationUrl.lastIndexOf('/')+1);
        
        String [] dbserverHosts = dbserverHostsStr.split(",");
        
        masterUrl = driverPrefix +"//" + dbserverHosts[0] +"/" + databaseOpts;
        
        logger.debug("{master url} " + masterUrl);
        
        for(int i=1;i<dbserverHosts.length;i++){
            String slaverUrl = driverPrefix +"//" + dbserverHosts[i] +"/" + databaseOpts;
            slaverUrlList.add(slaverUrl);
            logger.debug("{slaver url} " + slaverUrl);
        }
    }
    
    public String getMasterUrl(){
        return masterUrl;
    }
    
    public String getSlaverUrl(int index){
        return slaverUrlList.get(index);
    }
    
    public int getSlaverCount(){
        return slaverUrlList.size();
    }
    
    public String[] getSlaverUrlAsArray(){
        int count = getSlaverCount();
        if(count == 0)return null;
        
        String[] result = new String[count];
        for(int i=1;i<count;i++){
            result[i] = slaverUrlList.get(i);
        }
        return result;
    }
    
    public List<String> getSlaverUrl(){
        return slaverUrlList;
    }
}
